//
//  CBCentralManager+Rx.swift
//  RXSwiftDemo1
//
//  Created by mac on 2025/2/28.
//

import Foundation
import RxSwift
import RxCocoa
import CoreBluetooth


class RxCBCentralManagerDelegateProxy: DelegateProxy<CBCentralManager,CBCentralManagerDelegate>,DelegateProxyType,CBCentralManagerDelegate {
    
    var updateState = PublishSubject<BluetoothState>()
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        updateState.onNext(BluetoothState(rawValue: central.state.rawValue)!)
    }
    
    init(centeralManager: CBCentralManager) {
        super.init(parentObject: centeralManager, delegateProxy: RxCBCentralManagerDelegateProxy.self)
    }
    
    static func registerKnownImplementations() {
        self.register { centeralManager in
            RxCBCentralManagerDelegateProxy(centeralManager: centeralManager)
        }
    }
    
    static func currentDelegate(for object: CBCentralManager) -> CBCentralManagerDelegate? {
        return object.delegate
    }
    
    static func setCurrentDelegate(_ delegate: CBCentralManagerDelegate?, to object: CBCentralManager) {
        object.delegate = delegate
    }
    
}

extension Reactive where Base: CBCentralManager {
    public var delegate: DelegateProxy<CBCentralManager, CBCentralManagerDelegate> {
        return RxCBCentralManagerDelegateProxy.proxy(for: base)
    }
    
    // 蓝牙状态更新
    public var centralManagerDidUpdateState: Observable<BluetoothState> {
        return RxCBCentralManagerDelegateProxy.proxy(for: base).updateState.asObservable()
    }
    
    // 恢复状态
    public var willRestoreState: Observable<[String: Any]> {
        return delegate
            .methodInvoked(#selector(CBCentralManagerDelegate.centralManager(_:willRestoreState:)))
            .compactMap { $0[1] as? [String: Any] }
    }
    
    // 发现外设
    public var didDiscoverPeripheral: Observable<(CBPeripheral, [String: Any], NSNumber)> {
        return delegate
            .methodInvoked(#selector(CBCentralManagerDelegate.centralManager(_:didDiscover:advertisementData:rssi:)))
            .compactMap { ($0[1], $0[2], $0[3]) as? (CBPeripheral, [String : Any], NSNumber) }
    }
    
    // 连接外设成功
    public var didConnectPeripheral: Observable<CBPeripheral> {
        return delegate
            .methodInvoked(#selector(CBCentralManagerDelegate.centralManager(_:didConnect:)))
            .compactMap { $0[1] as? CBPeripheral }
    }
    
    // 连接外设失败
    public var didFailToConnectPeripheral: Observable<(CBPeripheral, Error)> {
        return delegate
            .methodInvoked(#selector(CBCentralManagerDelegate.centralManager(_:didFailToConnect:error:)))
            .compactMap { ($0[1], $0[2]) as? (CBPeripheral, any Error) }
    }
    
    // 断开外设连接
    public var didDisconnectPeripheral: Observable<(CBPeripheral, Error?)> {
        return delegate
            .methodInvoked(#selector(CBCentralManagerDelegate.centralManager(_:didDisconnectPeripheral:error:)))
            .compactMap { ($0[1], $0[2]) as? (CBPeripheral, (any Error)?) }
    }
    
    //监听连接状态的变化 event 参数提供了具体的事件类型，例如连接、断开连接等
    public var connectionEventDidOccur:Observable<(CBConnectionEvent,CBPeripheral)> {
        return delegate
            .methodInvoked(#selector(CBCentralManagerDelegate.centralManager(_:connectionEventDidOccur:for:)))
            .compactMap({( $0[1],$0[2] ) as? (CBConnectionEvent,CBPeripheral)})
    }
    
    // ANCS（Apple Notification Center Service）授权状态更新时调用,ANCS 允许蓝牙外设访问 iOS 设备的通知信息
    public var didUpdateANCSAuthorizationForPeripheral:Observable<CBPeripheral> {
        return delegate
            .methodInvoked(#selector(CBCentralManagerDelegate.centralManager(_:didUpdateANCSAuthorizationFor:)))
            .compactMap({ $0[1] as? CBPeripheral })
    }
}
